/**
 * @desc:普通充值弹窗
 * @author:binlety
 * * */

import { useState, useEffect, useMemo } from 'react';
import { Form, Input, Button, Modal, message } from 'antd';
import CommonLoading from '@/components/CommonLoading';
import IconFont from '@/components/IconFont';
import CommonModal from '@/components/CommonModal';
import { formatAmount, customTrimFunc } from '@/utils/utils.jsx';
import QRCode from 'qrcode.react';
import { getRechargeRateOp, rechargeOp, pollFuncOp } from '../../../service';
import styles from './index.module.less';

let timerPoll,
	showText,
	backAmount = '0.00';

export default ({ accountMsg = {}, visible, handleVisible, reloadFunc }) => {
	const [form] = Form.useForm();
	const [loading, setLoading] = useState(false);
	const [method, setMethod] = useState('alipay');

	const [rateObj, setRateObj] = useState({})//费率
	const [serviceFee, setFee] = useState('0.00') //手续费
	const [disAmount, setDisAmount] = useState('0.00') //优惠金额
	const [finallyAmount, setAmount] = useState('0.00') //实际付款金额

	const [qrcode, setQrcode] = useState('')//支付二维码

	const rote = useMemo(() => {
		if (Object.keys(rateObj).length) {
			return rateObj.weChatOrAliPayRate
		}
	}, [rateObj])

	const surplus = useMemo(() => {
		if (Object.keys(rateObj).length) {
			return rateObj.rechargeDiscount
		}
	}, [rateObj])

	useEffect(() => {
		if (visible) {
			getRechargeRateFunc()//费率
			form.resetFields()
		}
	}, [visible])

	//费率
	const getRechargeRateFunc = async () => {
		setLoading(true);
		const params = {};
		if(accountMsg.merchantNo) {
			params.accountNo = accountMsg.merchantNo;
			params.accountType = 2;
		}
		const { success, data = {} } = await getRechargeRateOp(params);
		let timer = setTimeout(() => {
			setLoading(false)
			clearTimeout(timer)
			timer = null
		}, 300)
		if (success) {
			setRateObj(data)
		}
	}

	//充值
	const onFinish = async () => {
		if (loading) {
			return
		}
		if (!rote || !surplus) {
			Modal.info({ content: '如若确保已经开通电子账户，请稍后再试' })
			return
		}
		form.validateFields(['amount']).then(async () => {
			const params = customTrimFunc({
				disAmount,
				payMeth: method == 'alipay' ? 2 : 3,
				orderSrc: 1,
				payAmount: Number(finallyAmount).toFixed(2),
				freeAmount: serviceFee,
				callBackNoticeUrl: PAY_CALLBACK_URL,
			})
			if(accountMsg.merchantNo) {
				params.accountNo = accountMsg.merchantNo;
				params.accountType = 2;
			}
			setLoading(true)
			const { success, data } = await rechargeOp(params)
			let timer = setTimeout(() => {
				setLoading(false)
				clearTimeout(timer)
				timer = null
			}, 300)
			if (success) {
				const { dimensionalCode, payOrderSn } = data
				setQrcode(dimensionalCode)
				timerPoll = setInterval(async () => {//充值后轮询
					const { data } = await pollFuncOp({ payOrderSn })
					if (data == 3) {
						closeQrCodeModal()
						closePayModal()
						reloadFunc()
					}
				}, 5000)
			}
		}).catch(() => {
			Modal.info({ content: '请按照要求输入充值金额' })
		})
	};

	//计算手续费 可到账金额
	const computeServiceFee = () => {
		form.validateFields(['amount']).then(async (res) => {
			const comp = Math.ceil(((res.amount * 100) * (rote * 10000)) / 10000) / 100;
			if (surplus && surplus - 0 >= comp) {//剩余额度够用
				showText = true
				backAmount = Math.ceil(res.amount * 100) / 100
				setFee('0.00')
				setDisAmount(Math.ceil(comp * 1000) / 1000)//防止数字类型的2.00 展示 2
				setAmount(res.amount)
				return
			}
			showText = false
			backAmount = (res.amount * 100 - Math.ceil(comp * 100)) / 100
			setFee(Math.ceil(comp * 1000) / 1000)
			setDisAmount('0.00')
			setAmount(res.amount)
		}).catch(() => {
			showText = false
			backAmount = '0.00'
			setFee("0.00")
			setAmount("0.00")
		})
	}

	//关闭支付弹窗
	const closePayModal = () => {
		backAmount = '0.00'
		handleVisible(false)
		setMethod('alipay')
		setRateObj({})
		setFee('0.00')
		setDisAmount('0.00')
		setAmount('0.00')
	}

	//关闭二维码弹窗
	const closeQrCodeModal = (bool) => {
		if (bool) {
			message.info('如已支付，后续请刷新查看最新余额')
		}
		setQrcode('')
		clearInterval(timerPoll)
		timerPoll = null
	}


	return (
		<>
			<CommonModal
				title="余额充值"
				visible={visible}
				onOk={onFinish}
				onCancel={closePayModal}
				width="458px"
			>
				<div className={styles.title}>支付方式</div>
				<div className={styles.payCard} style={{ background: method == 'alipay' ? '#EBF4FF' : '#fff' }} onClick={() => setMethod('alipay')}>
					<span className={styles.absolutedCenter}>
						<IconFont type="iconzhifubao" style={{ fontSize: 28, marginRight: 12 }} />
						<div style={{ paddingTop: '2px' }}>
							<p style={{ fontSize: '14px', lineHeight: '14px' }}>支付宝</p>
							<p className={styles.letter}>ALIPAY</p>
						</div>
					</span>
					{method == 'alipay' && <IconFont type='iconxuanzhongjiaobiao' className={styles.checkedBox} style={{ fontSize: 18 }} />}
				</div>

				<Form form={form} name="recharge-modal" style={{ display: 'flex', marginTop: 16 }}>
					<Form.Item label={<span className='lable-require'>充值金额</span>}>
						<div style={{ display: 'flex' }}>
							<Form.Item
								name="amount"
								rules={[
									{ required: true, message: '请输入充值金额' },
									({ }) => ({
										validator(rule, value) {
											if (value) {
												const reg = /^(?!0+(?:.0+)?$)(?:[1-9]\d*|0)(?:.\d{1,2})?$/;
												if (!reg.test(value)) {
													return Promise.reject('请正确输入，最多两位小数');
												}
												if (value > 1000000) {
													return Promise.reject('单笔限额一百万');
												}
												if (value <= 30) {
													return Promise.reject('充值金额需大于30元');
												}
											}
											return Promise.resolve();
										},
									}),
								]}
							>
								<Input suffix="元"
									autoComplete="off"
									onChange={() => computeServiceFee()}
									placeholder="请输入充值金额"
								/>
							</Form.Item>
							<span className={`${styles.rote} common-color8`}>(手续费费率：{rote ? `${rote * 100}%` : '***'})</span>
						</div>
					</Form.Item>
				</Form>

				<div style={{ display: 'flex', marginTop: 12 }}>
					<p style={{ width: '50%' }}>充值手续费：<span className='commom-color9' style={{ color: '#FF2D51' }}>￥{formatAmount(serviceFee)}</span></p>
					<p style={{ width: '50%' }}>实际到账金额：<span className='commom-color9' style={{ color: '#FF2D51' }}>￥{formatAmount(backAmount)}</span></p>
				</div>
				{showText ?
					<div className={styles.tipsBox}>
						<IconFont type='iconjingshi' style={{ paddingTop: '5px' }} />
						<span className={`${styles.textTips} common-color13`}>该笔充值手续费将由{APP_TITLE}平台补助给客户，若手续费补助额度不足手续费由自己承担，您的手续费剩余补助额度为￥{formatAmount(surplus)}</span><br />
					</div> : null
				}

			</CommonModal>

			<CommonModal
				title={`请用${method == 'vx' ? '微信' : '支付宝'}扫码充值`}
				visible={qrcode}
				footer={[<Button key='cancel' onClick={() => closeQrCodeModal(true)}>取消</Button>]}
				width="480px"
				onCancel={() => closeQrCodeModal(true)}
			>
				<QRCode value={qrcode} style={{ margin: '0 auto 12px' }} />
				<p style={{ textAlign: 'center' }}>需要支付金额为 <span style={{ color: 'red' }}>{formatAmount(finallyAmount)}</span> 元，实际到账金额将扣除手续费 <span style={{ color: 'red' }}>{formatAmount(serviceFee)}</span> 元</p>
			</CommonModal>
			<CommonLoading loading={loading} />
		</>
	);
};
